//
//  MusicLibraryViewController.m
//  CatMusic
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "MusicLibraryViewController.h"
#import "BaseCollectionViewCell.h"
#import "HeaderCollectionReusableView.h"
#import "UIImageView+WebCache.h"
#import "NetWorkingTool.h"
#import "NetWorkingToolMv.h"
#import "MVListViewController.h"
#import "RadioListViewController.h"
#import "MvPlayViewController.h"
#import "RadioTracksViewController.h"
#import "NightMode.h"
#import "AFNetworkReachabilityManager.h"
#import "PlayerSingleton.h"
#import "MJRefresh.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface MusicLibraryViewController ()<UICollectionViewDelegateFlowLayout, UIAlertViewDelegate>

@property(nonatomic, retain)NSMutableArray *arrMv;
@property(nonatomic, retain)NSMutableArray *arrRadio;
@property(nonatomic, retain)NSMutableArray *arrSinger;
@property(nonatomic, retain)UICollectionView *musicLibCollectionView;


@property (nonatomic , retain)UIView *myView;
@property (nonatomic , retain)UIImageView *imageView;


@end

@implementation MusicLibraryViewController


- (void)dealloc
{
    [_imageView release];
    [_myView release];
    [_arrMv release];
    [_arrRadio release];
    [_arrSinger release];
    [_musicLibCollectionView release];
    [super dealloc];
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrMv = [[NSMutableArray alloc] init];
        self.arrRadio = [[NSMutableArray alloc] init];
        self.arrSinger = [[NSMutableArray alloc] init];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"音乐库";
    
    // 夜间模式判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setLightDayModel) name:@"LightDayNSNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setNightDayModel) name:@"NightDayNSNotification" object:nil];
    
    if ([NightMode shareNightMode].isNight) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }

    // 音乐库的CollectView
    UICollectionViewFlowLayout *musicLibFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.musicLibCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(WIDTH / 375 * 10, HEIGHT / 667 * 20, WIDTH - 20, HEIGHT / 667 * 500) collectionViewLayout:musicLibFlowLayout];
    musicLibFlowLayout.itemSize = CGSizeMake(WIDTH / 375 * 100, HEIGHT / 667 * 120);
    musicLibFlowLayout.minimumLineSpacing = 20;
    musicLibFlowLayout.minimumInteritemSpacing = 10;
    musicLibFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    musicLibFlowLayout.headerReferenceSize = CGSizeMake(WIDTH / 375 * 20, 50);
    [self.musicLibCollectionView registerClass:[BaseCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.musicLibCollectionView.delegate = self;
    self.musicLibCollectionView.dataSource = self;
    self.musicLibCollectionView.tag = 1000;
    self.musicLibCollectionView.backgroundColor = [UIColor whiteColor];
    [self.musicLibCollectionView registerClass:[HeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];

//    [self creatDataMv];
//    [self creatDataRadio];
//    [self creatDataSinger];

    // 取消collectionview背景颜色
    self.musicLibCollectionView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:self.musicLibCollectionView];

    
    
#pragma mark - 判断网络状态    AFN
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                [self alertViewCancel];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                [self alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                [self creatDataMv];
                [self creatDataRadio];
                [self musicLibCollectionViewRefresh];
                break;
        }
    }];
    
    
    // 3.开始监控
    [mgr startMonitoring];
    [self animationImage];

    
}

// 下拉刷新
- (void)musicLibCollectionViewRefresh
{
    [self.musicLibCollectionView addLegendHeaderWithRefreshingBlock:^{
        // 延迟加载数据，2秒后才调用
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.musicLibCollectionView reloadData];
            
            // 结束刷新
            [self.musicLibCollectionView.header endRefreshing];
        });
        
    }];
}



- (void)alertViewCancel
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络断开连接" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    [alert show];
}

- (void)alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机自带网络" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    [alert show];
}





// 动画效果
- (void)animationImage
{
    self.myView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.myView.backgroundColor = [UIColor whiteColor];
//    self.myView.alpha = 0.5;
    [self.view addSubview:self.myView];
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH / 2 -100, HEIGHT / 2 - 100, WIDTH / 375 * 200, HEIGHT / 667 * 200)];
    [self.myView addSubview:self.imageView];
    NSMutableArray *imageArr = [NSMutableArray array];
    for (NSInteger i = 1; i < 56 ; i++) {
        NSString *imageName = [NSString stringWithFormat:@"a%ld.png" , (long)i];
        UIImage *image = [UIImage imageNamed:imageName];
        [imageArr addObject:image];
    }
    self.imageView.animationImages = imageArr;
    self.imageView.animationDuration = 1;
    [self.imageView startAnimating];
    [_imageView release];
}


// 设置页眉尺寸(需要签协议UICollectViewFlowLayout)
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize size = {WIDTH / 375 * 240, 30};
    return size;
}

// 页眉View
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    HeaderCollectionReusableView *headView;
    headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header" forIndexPath:indexPath];
    //    headView.backgroundColor = [UIColor orangeColor];
    
    if (indexPath.section == 0)
    {
        [headView setHeaderLabelText:@"MV"];
        UIButton *headerButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [headerButton setTitle:@"更多..." forState:UIControlStateNormal];
        headerButton.frame = CGRectMake(WIDTH / 375 * 270, 0, WIDTH / 375 * 100, 20);
        [headView addSubview:headerButton];
        [headerButton addTarget:self action:@selector(clickMV) forControlEvents:UIControlEventTouchUpInside];
    }
    if(indexPath.section == 1)
    {
        [headView setHeaderLabelText:@"电台"];
        UIButton *headerButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [headerButton setTitle:@"更多..." forState:UIControlStateNormal];
        headerButton.frame = CGRectMake(WIDTH / 375 * 270, 0, WIDTH / 375 * 100, 20);
        [headView addSubview:headerButton];
        [headerButton addTarget:self action:@selector(clickRadio) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self.myView removeFromSuperview];
    return headView;
    
}

- (void)clickMV
{
    NSLog(@"buttonMV");
    MvListViewController *mvList = [[MvListViewController alloc] init];
    // 传数据
//    mvList.arr = self.arrMv;
    [self.navigationController pushViewController:mvList animated:YES];
    [mvList release];
}

- (void)clickRadio
{
    NSLog(@"buttonRadio");
    RadioListViewController *radioList = [[RadioListViewController alloc] init];
    // 传数据
    radioList.arr = self.arrRadio;
    [self.navigationController pushViewController:radioList animated:YES];
    [radioList release];
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    if (self.arrRadio.count == 0) {
//        return 0;
//    }
    if (section == 0) {
        return  self.arrMv.count;
    }
    else
        return (self.arrRadio.count / 3) * 3;
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 30, 0);
}


- (void)creatDataMv
{
    [NetWorkingToolMv netWorkingToolStr:@"http://api.dongting.com/channel/channel/mvs?page=1&size=9" block:^(id result) {
        NSMutableDictionary *dic = result;
        self.arrMv = [dic objectForKey:@"data"];
        [self.musicLibCollectionView reloadData];
    }];
    
}

// 电台解析数据
- (void)creatDataRadio
{
    [NetWorkingTool netWorkingToolStr:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=all&condition=hot&device=iPhone&page=1&per_page=20&status=0&tag_name=" block:^(id result) {
        NSMutableDictionary *dic = result;
        self.arrRadio = [dic objectForKey:@"list"];
        [self.musicLibCollectionView reloadData];
    }];
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    BaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];

    if (indexPath.section == 0) {
        cell.baseTitleCollection.text = self.arrMv[indexPath.row][@"videoName"];
        NSString *str = self.arrMv[indexPath.row][@"bigPicUrl"];
        NSURL *url = [NSURL URLWithString:str];
        [cell.baseImageViewCollection sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeHolder"]];
    }
    
    else if (indexPath.section == 1)
    {
        NSString *str = self.arrRadio[indexPath.row][@"albumCoverUrl290"];
        NSURL *url = [NSURL URLWithString:str];
        [cell.baseImageViewCollection sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeHolder"]];
        cell.baseTitleCollection.text = self.arrRadio[indexPath.row][@"title"];
    }
    
    return cell;
}

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
//    NSLog(@"%ld", indexPath.section);
    if (indexPath.section == 0) {
        // 跳转MV播放页面
        [[PlayerSingleton sharePlayerSingleton].player pause];
        MvPlayViewController *mvPlayVC = [[MvPlayViewController alloc] init];
        NSString *url = self.arrMv[indexPath.row][@"mvList"][0][@"url"];
        mvPlayVC.url = url;
        [self.navigationController pushViewController:mvPlayVC animated:YES];
        [mvPlayVC release];
    }
    else if(indexPath.section == 1)
    {
        // 跳转电台列表页面
        RadioTracksViewController *radioTracks = [[RadioTracksViewController alloc] init];
        NSString *idNum = self.arrRadio[indexPath.row][@"id"];
        NSString *urlHead = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@", idNum];
        NSString *url = [NSString stringWithFormat:@"%@/true/1/30?device=iPhone", urlHead];
        radioTracks.url = url;
        [self.navigationController pushViewController:radioTracks animated:YES];
        [radioTracks release];
            
    }

    
}


- (void)setLightDayModel
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    
    UIColor * color = [UIColor blackColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
    

}

- (void)setNightDayModel
{
    self.view.backgroundColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
 
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];

    
     UIColor * color = [UIColor whiteColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;

    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
